   import flash.events.Event;
   import flash.media.Sound;
   import flash.media.SoundChannel;

import Sounds;

    class SoundPlayer
    {

	private var State:Int;
        private var sound:Sound;
	private var sound1:Sound;
	private var sound2:Sound;
	private var sound3:Sound;
	private var sound4:Sound;
        private var ch:SoundChannel;
        private var isSoundPlaying:Bool;
	private var currentTrack:Int;

        public function new(inState:Int)
        {
	    sound1 = new NormalMusic();
	    sound2 = new FadeDownMusic();
	    sound3 = new MixMusic();
	    sound4 = new BoringMusic();
            sound = sound1;
	    State = inState;
	    currentTrack =1;
            isSoundPlaying = false;
	    getNextTrack();
        } 

        public function getPosition():Float
        {
          return ch.position;
        }

        public function play(inPosition:Float)
        {
            if(!isSoundPlaying)
            {
                ch = sound.play(inPosition);
                ch.addEventListener(
                    Event.SOUND_COMPLETE,
                    handleSoundComplete);
                isSoundPlaying = true;
            }
        }

        public function stop()
        {
            if(isSoundPlaying)
            {
		ch.removeEventListener(
                    Event.SOUND_COMPLETE,
                    handleSoundComplete);
                ch.stop();
                isSoundPlaying = false;
            }
        }

        public function increaseState()
	{
	  State++;
	  stop();
	  getNextTrack();
	  if(State == 2)
	    {sound=sound2;}
	  play(0);
	}
	private function getNextTrack()
	{

            if(State <= 2)
	      {sound = sound1;play(0);}
	    if(State == 3)
	      {
		if(currentTrack == 1)
		  {sound = sound2;currentTrack=2;}
		else
		  {sound = sound1;currentTrack=1;}
	      }
	    if(State == 4)
	      {sound = sound3;currentTrack=3;}
	    if(State >= 5)
	      {sound = sound4;currentTrack=4;}
	}

        private function handleSoundComplete(ev:Event)
        {
	    ch.removeEventListener(
	    Event.SOUND_COMPLETE,
	    handleSoundComplete);
            isSoundPlaying = false;
	    getNextTrack();
	    play(0);
        }
    }
